<template>
  <div class="page-container">
    <a-flex :vertical="true">
      <a-card style="width: 100%;">
        <a-form ref="formRef" name="advanced_search" class="ant-advanced-search-form"
                :model="formState" layout="inline">
          <a-flex wrap="wrap" gap="small">
            <a-form-item name="role_name" label="角色">
              <a-input placeholder="请输入角色名"></a-input>
            </a-form-item>

            <a-button type="primary" html-type="submit">搜索</a-button>
          </a-flex>

        </a-form>
      </a-card>

      <a-card style="width: 100%; margin: 12px 0 12px 0; min-height: calc(100vh - 250px);">
        <a-row :gutter="18">
          <a-col>
            <a-button type="primary" @click="handleAdd">新建角色</a-button>
          </a-col>
          <a-col>
            <a-button @click="handleBatchDelete">批量删除</a-button>
          </a-col>
        </a-row>
        <br />
        <a-table :columns="columns" :data-source="rolesListData?.records" bordered
                 :row-selection="rowSelection"
                 :pagination="{defaultCurrent: 1, defaultPageSize: 10, showSizeChanger: true, showQuickJumper: true, total: rolesListData.total, showTotal: (total:number) => `共${total}条`}">
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'password'">
              <a-space size="small">
                <a-input-password v-model:value="record.password" v-model:visible="record.visible"
                                  :visibility-toggle="false" :bordered="false" />
                <a @click="record.visible = !record.visible">
                  <EyeOutlined v-if="record.visible" />
                  <EyeInvisibleOutlined v-else />
                </a>
              </a-space>
            </template>
            <template v-else-if="column.key === 'tags'">
                <span>
                  <a-tag v-for="tag in record.tags" :key="tag"
                         :color="tag === 'loser' ? 'volcano' : tag.length > 5 ? 'geekblue' : 'green'">
                    {{ tag.toUpperCase() }}
                  </a-tag>
                </span>
            </template>
            <template v-else-if="column.key === 'action'">
                <span>
                  <a @click="handleEdit(record)">编辑</a>
                  <a-divider type="vertical" />
                  <a @click="handleDelete(record)">删除</a>
                </span>
            </template>
          </template>
        </a-table>
      </a-card>
    </a-flex>


    <a-modal
      v-model:open="permissionModelFormState.visible"
      :title="permissionModelFormState.title"
      width="65%"
      centered
      :footer="null"
    >
      <div style="margin-top:24px">
        <a-form
          :model="permissionModelFormState.formModel"
          name="basic"
          autocomplete="off"
          size="large"
          :label-col="{ span: 4 }"
          ref="permissionFromRef"
        >
          <a-form-item
            label="角色ID"
            name="id"
            v-if="permissionModelFormState.type !== 'add'"
          >
            {{ permissionModelFormState.formModel.id }}
          </a-form-item>

          <a-form-item
            label="角色标识"
            name="roleCode"
            :rules="[{ required: true, message: '请输入角色标识' }]"
          >
            <a-input
              placeholder="请输入角色名称"
              v-model:value="permissionModelFormState.formModel.roleName"
            />
          </a-form-item>

          <a-form-item
            label="角色名称"
            name="roleName"
            :rules="[{ required: true, message: '请输入角色名称' }]"
          >
            <a-input
              placeholder="请输入角色名称"
              v-model:value="permissionModelFormState.formModel.roleName"
            />
          </a-form-item>

          <a-form-item
            label="角色描述"
            name="description"
            :rules="[{ required: true, message: '请输入角色描述' }]"
          >
            <a-textarea v-model:value="permissionModelFormState.formModel.description"
                        placeholder="请输入角色描述" />
          </a-form-item>

          <a-form-item
            label="权限"
            name="permissions"
          >
            <a-row :gutter="18">
              <a-col :span="4">
                <a-button block size="middle">添加</a-button>
              </a-col>
            </a-row>
            <br/>
            <a-row :gutter="16">
              <a-col :span="24">
                <a-table size="small" :columns="permissionModelFormState.columns"
                         :data-source="permissionModelFormState.formModel.permissions.records" bordered
                         :pagination="{defaultCurrent: 1, defaultPageSize: 10, showSizeChanger: true, showQuickJumper: true, total: permissionModelFormState.formModel.permissions.total, showTotal: (total:number) => `共${total}条`}">
                  <template #bodyCell="{ column, record }">
                    <template v-if="column.dataIndex === 'permissionId'">
                      {{record.permissionId || ''}}
                    </template>

                    <template v-if="column.key === 'action'">
                      <span>
                        <a @click="permissionModelFormState.formModel.permissions.records = permissionModelFormState.formModel.permissions.records.filter((item) => item?.id != record?.id)">删除</a>
                      </span>
                    </template>
                  </template>
                </a-table>

              </a-col>
            </a-row>
          </a-form-item>

          <a-form-item :wrapper-col="{ offset: 4 }" style="margin-bottom: 32px">
            <a-row :gutter="16">
              <a-col :span="12">
                <a-button
                  @click="permissionFromRef.resetFields();permissionModelFormState.visible = false"
                  :block="true">
                  取消
                </a-button>
              </a-col>
              <a-col :span="12">
                <a-button type="primary" block @click="addRolePermissions">
                  提交
                </a-button>
              </a-col>
            </a-row>
          </a-form-item>
        </a-form>
      </div>
    </a-modal>


  </div>
</template>

<script lang="ts" setup>
import { computed, nextTick, onActivated, reactive, ref } from 'vue'
import { EyeOutlined, EyeInvisibleOutlined } from '@ant-design/icons-vue'

import { rolesApi } from '@/api/roles'
import notification from 'ant-design-vue/es/notification'


const columns = [
  {
    title: '角色ID',
    dataIndex: 'id',
    key: 'id'
  },
  {
    title: '角色',
    dataIndex: 'roleCode',
    key: 'roleCode'
  },
  {
    title: '角色名称',
    dataIndex: 'roleName',
    key: 'roleName'
  },
  {
    title: '角色备注',
    dataIndex: 'description',
    key: 'description'
  },
  // {
  //   title: '创建人',
  //   dataIndex: 'createdUserId',
  //   key: 'createdUserId',
  // },
  // {
  //   title: '创建时间',
  //   key: 'createdTime',
  //   dataIndex: 'createdTime',
  // },
  // {
  //   title: '更新时间',
  //   key: 'updatedTime',
  //   dataIndex: 'updatedTime',
  // },
  {
    title: '操作',
    key: 'action'
  }
]

const state = reactive<{
  selectedRowKeys: string | number[];
  loading: boolean;
}>({
  selectedRowKeys: [], // Check here to configure the default column
  loading: false
})

const onSelectChange = (selectedRowKeys: string | number[]) => {
  state.selectedRowKeys = selectedRowKeys
}
const rowSelection = computed(() => ({
  selectedRowKeys: state.selectedRowKeys,
  onChange: onSelectChange
}))

const formState = reactive({
  name: ''
})
const rolesListData = reactive({
  records: [],
  total: 0,
  pageNum: 1,
  pageSize: 10
})
const getRolesList = async () => {
  const res = await rolesApi.listRoles({
    pageNum: 1,
    pageSize: 10,
    ...formState
  })
  console.log(res)
  if (res?.code === 200) {
    console.log(JSON.stringify(res))
    rolesListData.total = res?.data?.total
    rolesListData.pageNum = res?.data?.pageNum
    rolesListData.pageSize = res?.data?.pageSize
    rolesListData.records = res?.data?.records
  }
}

onActivated(() => {
  getRolesList()
})


const permissionFromRef = ref()
const permissionModelFormState = reactive({
  visible: false,
  formModel: {
    id: '',
    roleCode: '',
    permissions: {
      records: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      pages: 0
    },
    roleName: '',
    description: ''
  },
  title: '添加权限',
  type: 'add',
  columns: [
    {
      title: '权限编码',
      dataIndex: 'permissionCode'
    },
    {
      title: '权限名称',
      dataIndex: 'permissionName'
    },
    {
      title: '权限描述',
      dataIndex: 'permissionDesc'
    },
    {
      title: '操作',
      key: 'action',
    }
  ]
})


const resetPermissionModelFormState = () => {
  permissionFromRef.value.resetFields()
  permissionModelFormState.formModel = {
    id: '',
    roleCode: '',
    permissions: {
      records: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      pages: 0
    },
    roleName: '',
    description: ''
  }
}


const getRolesPermissions = async (roleId: string) => {
  const res = await rolesApi.listRolesPermissions({ pageNum: permissionModelFormState?.formModel?.permissions?.pageNum, pageSize: permissionModelFormState?.formModel?.permissions?.pageSize, roleId })
  console.log(res)
  if (res?.code === 200) {
    permissionModelFormState.formModel.permissions.records = res?.data?.data
    permissionModelFormState.formModel.permissions.total = res?.data?.total
    permissionModelFormState.formModel.permissions.pages = res?.data?.pages
  } else {
    notification.error({
      message: res?.message || '获取权限列表失败'
    })
  }
}

const handleEdit = async (record: any) => {
  // 编辑权限信息
  console.log(record)
  permissionModelFormState.type = 'edit'
  permissionModelFormState.formModel.id = record.id
  permissionModelFormState.formModel.roleName = record.roleName
  permissionModelFormState.formModel.roleCode = record.roleCode
  permissionModelFormState.formModel.description = record.description
  await getRolesPermissions(record.id)
  permissionModelFormState.title = '编辑角色权限'
  permissionModelFormState.visible = true
}


const handleDelete = async (record: any) => {
  const res = await rolesApi.deleteRoles({ id: record.id })
  if (res?.code === 200) {
    notification.success({
      message: '删除成功'
    })
    getRolesList()
  } else {
    notification.error({
      message: res?.message || '删除失败'
    })
  }
}

const handleAdd = async () => {
  // 添加权限信息
  permissionModelFormState.type = 'add'
  permissionModelFormState.title = '添加角色'
  permissionModelFormState.visible = true
  await nextTick()
  resetPermissionModelFormState()
}

const addRolePermissions = async (record: any) => {
  console.log(record)
}

const handleBatchDelete = async () => {
  // 批量删除
  console.log('批量删除')
}


</script>

<style scoped lang="less">
.page-container {
  width: 100%;
  height: 100%;
}
</style>
